/* app05-window.c
 *
 * Copyright 2024 wan-iot
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "main-window.h"
#include "../entity/user.h"
#include "product.h"
#include <sqlite3.h>
struct _MainWindow
{
  GtkApplicationWindow  parent_instance;
  

  /* Template widgets */
 // GtkHeaderBar        *header_bar;
  //GtkLabel            *label;
  GtkBox *main_box;
  //GtkBox *main_title_box;
  //GtkButtonBox *user_box;
  //GtkLabel *username_lbl;
  GtkLinkButton *btn_quit;
  //GtkSeparator *main_sp;
  GtkNotebook *main_note;
  //GtkLabel *home_lbl;
  //GtkLabel *user_lbl;
  GtkTreeView *view_product;
 // GtkLabel *product_lbl;
  //GtkLabel *apply_lbl;
  //GtkLabel *pwd_update_lbl;
  //GtkLabel *lbl_copy;
  GtkListStore *product_store;
  GtkMenu *tree_menu;
  GtkMenuItem *update;
  GtkMenuItem *delete;
  GtkDialog *product_update_dialog;
  GtkEntry *prod_id_input;
  GtkEntry *prod_name_input;
  GtkEntry *prod_price_input;
  GtkEntry *prod_num_input;
  GtkEntry *prod_apply_input;
  GtkEntry *prod_address_input;
  GtkButton *prod_cancel_btn;
  GtkButton *prod_update_btn;
  GtkButton *prod_add_btn;
  GtkMessageDialog *prod_msg_dialog;
  GtkButton *prod_dialog_open_btn;

};


G_DEFINE_TYPE (MainWindow, main_window, GTK_TYPE_APPLICATION_WINDOW)

static void
main_window_class_init (MainWindowClass *klass)
{
  GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
  gtk_widget_class_set_template_from_resource (widget_class, "/a/b/c/main/main-window.ui");
  //gtk_widget_class_bind_template_child (widget_class, MainWindow, main_box);
  //gtk_widget_class_bind_template_child (widget_class, MainWindow, main_title_box);
  //gtk_widget_class_bind_template_child (widget_class, MainWindow,user_box );
  //gtk_widget_class_bind_template_child (widget_class, MainWindow, username_lbl);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, btn_quit);

  gtk_widget_class_bind_template_child (widget_class, MainWindow, main_note);

  gtk_widget_class_bind_template_child (widget_class, MainWindow, view_product);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, tree_menu);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, product_store);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, update);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, delete);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, product_update_dialog);
  
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_id_input);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_name_input);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_price_input);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_num_input);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_apply_input);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_address_input);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_cancel_btn);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_update_btn);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_msg_dialog);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_dialog_open_btn);
  gtk_widget_class_bind_template_child (widget_class, MainWindow, prod_add_btn);
}

GtkTreeView *product_view;
GtkListStore *product_store;
GtkWidget *prod_update_dialog;//修改商品的对话框
GtkEntry *prod_id_input;
GtkEntry *prod_name_input;
GtkEntry *prod_price_input;
GtkEntry *prod_num_input;
GtkEntry *prod_apply_input;
GtkEntry *prod_address_input;
GtkButton *prod_update_btn;
GtkMessageDialog *prod_msg_dialog;
GtkButton *prod_add_btn;
void emit_signal(MainWindow *self,gpointer data){
  //判断窗体
  g_assert (GTK_IS_APPLICATION_WINDOW (self));
  User* loginUser;
  loginUser = malloc(sizeof(User));
  loginUser = data?(User*)data:NULL;
  g_print("main窗体：id=%d,name=%s\n",loginUser->id,loginUser->name);
}
gboolean main_quit(){
  g_print("关闭主窗体...\n");
  //显示登录窗体
  return FALSE;
}
void handle_destroy(MainWindow *self,gpointer data){
   g_assert (GTK_IS_APPLICATION_WINDOW (self));
  GtkWidget*login_window = (GtkWidget*)data;
  g_print("显示登录窗体:\n");
  gtk_widget_show (login_window);
}

void load_product_data(gpointer data,int rows,int cols,char **result){
  GtkTreeIter iter;
      int count =cols-1;//6
      printf("count=%d\n",count);
      printf("rows=%d\n",rows);
      printf("result[6]=%s\n",result[7]);
      GtkListStore *store = GTK_LIST_STORE (data);
      gtk_list_store_clear (store);
      for(int i=0;i<rows;i++){
      gtk_list_store_append(store,&iter);
      char id[10];
      char name[20];
      char price[10];
      char apply[50];
      char address[100];
      char num[10];
      strcpy(id,result[++count]);
      strcpy(name,result[++count]);
      strcpy(price,result[++count]);
      strcpy(num,result[++count]);
      strcpy(apply,result[++count]);
      strcpy(address,result[++count]);

      printf("id=%s,name=%s\n",id,name);
      gtk_list_store_set(store,&iter,0,id,1,name,2,price,3,num,4,apply,5,address,-1);
      }
     sqlite3_free_table (result);
}

void click_product(GtkNotebook*book,gpointer page,guint num,gpointer data){
  if(num==2){
      //显示商品信息：查询数据库
      char *sql = "select * from product";
      char** result;
      int rows;
      int cols;
      query_prod_list (sql, &result, &rows, &cols);
      //设置treeview

      // gtk_list_store_append(GTK_LIST_STORE (store),&row);
      //为这一行添加数据
      // gtk_tree_store_set(GTK_TREE_STORE(store), &iter,
       //                      col_name, text,
         //                      -1);
      //GtkTreeStore *store = GTK_TREE_STORE (gtk_tree_view_get_model(product_view));
      //g_print("store=%p\n",store);
      //加载数据
      load_product_data (data, rows, cols, result);
      //sqlite3_free_table (result);
  }

    /* gtk_tree_store_append(store,&iter,NULL); */
    /* gtk_tree_store_set(store,&iter,0,2,1,"小明",2,4.5,-1); */
    /* gtk_tree_store_append(store,&iter,NULL); */
    /* gtk_tree_store_set(store,&iter,0,3,1,"小王",2,2.5,-1); */
  return;
}

gboolean open_menu(GtkTreeView *view,GdkEventButton *event,gpointer data){

  if(event->button == 3){
    printf("right clicked...\n");
    GtkWidget* menu = GTK_WIDGET (data);
    //弹出快捷菜单
   gtk_menu_popup_at_pointer(GTK_MENU(menu), (GdkEvent *)event);
  }
   return FALSE;
}

//创建模型
/* GtkTreeModel *createGtkTreeModel(){ */

/*   GtkTreeStore *store; */
/*   //设置六列 */
/*   store = gtk_tree_store_new(6,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING); */
/*   return GTK_TREE_MODEL (store); */
/* } */


//显示修改商品对话框的数据初始化
/* void prod_update_init(GtkDialog *prod_update_dialog,gpointer data){ */
/*   printf("init...\n"); */
/*    gtk_editable_set_editable (GTK_EDITABLE (prod_id_input), TRUE); */
/*   // ...判断是修改还是删除 */
/*   char** result = (char **)data; */
/*   gtk_entry_set_text (prod_id_input, result[6]); */
/*   //设置不可修改 */
/*   gtk_editable_set_editable (GTK_EDITABLE (prod_id_input), FALSE); */


/* } */



//选择修改
void select_update(GtkMenuItem *item,GdkEventButton*event,gpointer data_view_product){

  //GtkWidget* view = GTK_WIDGET (data);
  GtkTreeSelection *selection =  gtk_tree_view_get_selection (GTK_TREE_VIEW (data_view_product));
  GtkTreeIter iter;
  GtkTreeModel *model;

  if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
      gchar *value;
      gtk_tree_model_get(model, &iter, 0, &value, -1);//获取这行中的id值
      g_print("Selected value: %s\n", value);
      //进行查询商品
      char** result;
      int rows;
      int cols;
      char *sql = sqlite3_mprintf ("select * from product where prod_id='%q'",value);
      query_prod_list (sql, &result, &rows, &cols);
      g_free(value);
      //GtkListStore *store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW (data_view_product)));
      //load_product_data (store, rows, cols, result);
      // 加载数据
      gtk_entry_set_text (prod_id_input, result[6]);
      //设置不可修改
      gtk_editable_set_editable (GTK_EDITABLE (prod_id_input), FALSE);
      gtk_entry_set_text (prod_name_input, result[7]);
      gtk_entry_set_text (prod_price_input, result[8]);
      gtk_entry_set_text (prod_num_input, result[9]);
      gtk_entry_set_text (prod_apply_input, result[10]);
      gtk_entry_set_text (prod_address_input, result[11]);
      gtk_widget_hide (GTK_WIDGET (prod_add_btn));
      //弹出对话框
      gtk_window_set_title (GTK_WINDOW (prod_update_dialog), "修改商品信息");
      //隐藏新增按钮
      gtk_widget_hide (GTK_WIDGET (prod_add_btn));
      //显示修改按钮
      gtk_widget_show(GTK_WIDGET (prod_update_btn));


      gtk_widget_show (prod_update_dialog);
      sqlite3_free_table (result);

  }

}
gboolean click_hide_dialog(GtkDialog* prod_update_dialog,gpointer data){
    //隐藏修改商品的对话框
    gtk_widget_hide (GTK_WIDGET (prod_update_dialog));
    return TRUE;
}
void prod_update_cancel(GtkButton *prod_cancel_btn,gpointer prod_update_dialog){
  //隐藏修改商品的对话框
    gtk_widget_hide (GTK_WIDGET (prod_update_dialog));
}
//修改操作
void prod_update_save(){
  gchar *name =(char *)gtk_entry_get_text (prod_name_input);
  gchar *price =(char *)gtk_entry_get_text (prod_price_input);
  gchar *num =(char *)gtk_entry_get_text (prod_num_input);
  gchar *apply =(char *)gtk_entry_get_text (prod_apply_input);
  gchar *address =(char *)gtk_entry_get_text (prod_address_input);
  gchar *id =(char *)gtk_entry_get_text (prod_id_input);
  char* sql =  g_strdup_printf ("update product set prod_name='%s',price='%s',prod_num='%s',prod_apply_name='%s',prod_address='%s' where prod_id='%s'", name,price,num,apply,address,id);
  printf("update-sql:%s\n",sql);
  int res = prod_update(sql);
  if(!res){
     gtk_widget_hide (prod_update_dialog);
    //弹出消息框
    gtk_message_dialog_format_secondary_text (prod_msg_dialog, "修改商品成功");
    gtk_widget_show (prod_msg_dialog);
    //查询数据库
    //显示商品信息：查询数据库
    //使用信号回调处理
      /* char *sql = "select * from product"; */
      /* char** result; */
      /* int rows; */
      /* int cols; */
      /* query_prod_list (sql, &result, &rows, &cols); */
      /* //加载数据 */
      /* load_product_data (product_store, rows, cols, result); */

  }
}
void close_prod_msg_dialog(GtkButton *btn,gpointer data){
  printf("mmm\n");
  gtk_widget_hide (GTK_WIDGET (data));
}
/**显示新增窗口*/
void open_add_dialog(GtkButton *btn,gpointer data){
  printf("bb\n");
  gtk_window_set_title (GTK_WINDOW (prod_update_dialog), "新增商品信息");
  gtk_widget_hide(GTK_WIDGET (prod_update_btn));//隐藏修改按钮
  gtk_widget_show(GTK_WIDGET(prod_add_btn));

  //清空gtkentry中的数据
  gtk_entry_set_text (prod_id_input, "后台自动生成");
  gtk_entry_set_text (prod_name_input, "");
  gtk_entry_set_text (prod_price_input, "");
  gtk_entry_set_text (prod_num_input, "");
  gtk_entry_set_text (prod_apply_input, "");
  gtk_entry_set_text (prod_address_input, "");
  gtk_widget_show (prod_update_dialog);
  gtk_editable_set_editable (GTK_EDITABLE (prod_id_input), FALSE);
}
/*新增保存*/
void prod_add_save(){
  printf("add..\n");
  gchar *name =(char *)gtk_entry_get_text (prod_name_input);
  gchar *price =(char *)gtk_entry_get_text (prod_price_input);
  gchar *num =(char *)gtk_entry_get_text (prod_num_input);
  gchar *apply =(char *)gtk_entry_get_text (prod_apply_input);
  gchar *address =(char *)gtk_entry_get_text (prod_address_input);
  //gchar *id =(char *)gtk_entry_get_text (prod_id_input);
  char *sql = sqlite3_mprintf ("insert into product(prod_name,price,prod_num,prod_apply_name,prod_address) "\
        "values('%q','%q','%q','%q','%q');",name,price,num,apply,address);
  int res = prod_add(sql);
  if(res){
    // ...失败
  }else{
    gtk_widget_hide (GTK_WIDGET (prod_update_dialog));
    gtk_message_dialog_format_secondary_text (prod_msg_dialog, "新增商品成功");
    //gtk_native_dialog_set_title (GTK_NATIVE_DIALOG (prod_msg_dialog), "");
    gtk_widget_show (GTK_WIDGET (prod_msg_dialog));
  }
}
void view_reload_data(){
  //显示商品信息：查询数据库
      char *sql = "select * from product";
      char** result;
      int rows;
      int cols;
      query_prod_list (sql, &result, &rows, &cols);
      //加载数据
      load_product_data (product_store, rows, cols, result);
}
//选择删除
void select_delete(GtkMenuItem *item,GdkEventButton*event,gpointer data_view_product){

  //GtkWidget* view = GTK_WIDGET (data);
  GtkTreeSelection *selection =  gtk_tree_view_get_selection (GTK_TREE_VIEW (data_view_product));
  GtkTreeIter iter;
  GtkTreeModel *model;

  if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
      gchar *value;
      gtk_tree_model_get(model, &iter, 0, &value, -1);//获取这行中的id值
      g_print("Selected value: %s\n", value);
      //进行删除商品

      char *sql = sqlite3_mprintf ("delete  from product where prod_id='%q'",value);
     int res = prod_delete (sql);
      if(res){
        // 失败。。。
      }else{
        gtk_message_dialog_format_secondary_text (prod_msg_dialog, "删除成功");
        gtk_widget_show (GTK_WIDGET (prod_msg_dialog));

      }



  }

}

static void
main_window_init (MainWindow *self)
{
  gtk_widget_init_template (GTK_WIDGET (self));
  product_store = self->product_store;
  prod_update_dialog = GTK_WIDGET (self->product_update_dialog);
  prod_id_input = self->prod_id_input;
  prod_name_input = self->prod_name_input;
  prod_price_input = self->prod_price_input;
  prod_num_input = self->prod_num_input;
  prod_apply_input = self->prod_apply_input;
  prod_address_input = self->prod_address_input;
  prod_msg_dialog = self->prod_msg_dialog;
  prod_update_btn = self->prod_update_btn;
  prod_add_btn = self->prod_add_btn;
  //窗体最大化
  //gtk_window_maximize (GTK_WINDOW (self));
  //gtk_window_set_title ((GtkWindow *)self, "ok");
  
  //g_object_get(GTK_WIDGET (self), "loginUser", &loginUser, NULL);
 // g_print("name=%s\n",self->name);
  //关闭主窗体的关联信号处理
  g_signal_connect (self, "delete_event", G_CALLBACK(main_quit), NULL);
  
  g_signal_connect (self->main_note, "switch-page", G_CALLBACK(click_product), self->product_store);
  //默认显示第1页
  gtk_notebook_set_current_page(GTK_NOTEBOOK(self->main_note),2);
  product_view = self->view_product;
  //绑定model
  //gtk_tree_view_set_model(GTK_TREE_VIEW (product_view),GTK_TREE_MODEL (self->product_store));
  gtk_tree_view_set_model(GTK_TREE_VIEW (self->view_product),GTK_TREE_MODEL(self->product_store));

  //GtkTreeModel *store =  createGtkTreeModel ();
  GtkCellRenderer *renderer;
  renderer = gtk_cell_renderer_text_new();

   GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes("id", renderer, "text", 0, NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(self->view_product), column);

  column = gtk_tree_view_column_new_with_attributes("商品名称", renderer, "text", 1, NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(self->view_product), column);

  column = gtk_tree_view_column_new_with_attributes("商品价格", renderer, "text", 2, NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(self->view_product), column);

  column = gtk_tree_view_column_new_with_attributes("商品库存", renderer, "text", 3, NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(self->view_product), column);

  column = gtk_tree_view_column_new_with_attributes("商品供应商", renderer, "text", 4, NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(self->view_product), column);

  column = gtk_tree_view_column_new_with_attributes("商品产地", renderer, "text", 5, NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(self->view_product), column);

  //绑定右键弹出右键快捷菜单
  g_signal_connect (GTK_TREE_VIEW (self->view_product), "button-press-event", G_CALLBACK(open_menu), self->tree_menu);
  //选择修改
  g_signal_connect (GTK_MENU_ITEM (self->update), "button-press-event", G_CALLBACK(select_update), self->view_product);
  //选择删除
  g_signal_connect (GTK_MENU_ITEM (self->delete), "button-press-event", G_CALLBACK(select_delete), self->view_product);

  //修改商品对话框的关闭信号回调
  g_signal_connect (GTK_DIALOG (self->product_update_dialog), "delete_event", G_CALLBACK(click_hide_dialog), NULL);

  //商品对话框取消按钮信号处理
  g_signal_connect (GTK_BUTTON(self->prod_cancel_btn), "clicked", G_CALLBACK(prod_update_cancel), self->product_update_dialog);

  //商品对话框修改按钮信号处理
  g_signal_connect (GTK_BUTTON(self->prod_update_btn), "clicked", G_CALLBACK(prod_update_save), self->prod_update_btn);
  // 获取OK按钮
  GtkWidget *ok_button = gtk_dialog_get_widget_for_response(GTK_DIALOG(self->prod_msg_dialog), GTK_RESPONSE_OK);

  g_signal_connect (ok_button, "clicked", G_CALLBACK(close_prod_msg_dialog), GTK_WIDGET (self->prod_msg_dialog));

  g_signal_connect(self->prod_dialog_open_btn,"clicked",G_CALLBACK(open_add_dialog),NULL);
  //新增信号
   g_signal_connect(self->prod_add_btn,"clicked",G_CALLBACK(prod_add_save),NULL);

  //每次让消息框消失时
  g_signal_connect(self->prod_msg_dialog,"hide",G_CALLBACK(view_reload_data),NULL);
}

